package com.situ.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.common.util.MD5Util;
import com.situ.crm.entity.User;
import com.situ.crm.entity.UserRole;
import com.situ.crm.mapper.UserMapper;
import com.situ.crm.mapper.UserRoleMapper;
import com.situ.crm.service.IUserService;
import com.situ.crm.vo.ResultDataVO;

//用户服务实现类
@Service("userService")
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public User doLogin(String username, String password) {
		User user = userMapper.selectByUsername(username);
		if (user == null) {
			return null;
		}
		if (user.getPassword().equals(MD5Util.md5(password))) {
			return user;
		}
		return null;
	}

	@Override
	public ResultDataVO selectUserList(String username, Integer page, Integer limit) {
		ResultDataVO result = new ResultDataVO();
		PageHelper.startPage(page, limit);
		List<User> userList = userMapper.selectUsers(username);
		result.setData(userList);
		PageInfo<User> pageInfo = new PageInfo<>(userList);
		result.setCount(pageInfo.getTotal());
		return result;
	}

	@Override
	public void delUser(Integer id) {
		userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void save(User user) {
		if (user.getId() == null) {
			user.setPassword(MD5Util.md5("123456"));
			user.setStatus("1");
			userMapper.insert(user);
		} else {
			userMapper.updateByPrimaryKeySelective(user);
		}
	}

	@Override
	public User selectUserById(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void changeRole(Integer userId, Integer roleId, String type) {
		
		if ("add".equals(type)) {			
			userRoleMapper.insert(new UserRole(userId,roleId));
		}
		if ("remove".equals(type)) {
			userRoleMapper.removeRole(userId,roleId);
		}
	}

}
